<template>
  <el-drawer :model-value="modelValue" :title="mode === 'add' ? $t('trackMgr.addTrack') : $t('trackMgr.editTrack')"
    :size="1000" :close-on-click-modal="false" destroy-on-close :before-close="handleBeforeClose"
    @update:model-value="handleDrawerClose">
    <!-- 草稿提示栏 - 只在编辑模式且有草稿时显示 -->
    <div v-if="draft.hasDraft && mode === 'edit'"
      class="w-full h-[42px] bg-blue-100 flex justify-between items-center px-4 rounded-lg">
      <div class="flex items-center text-sm font-normal">
        <span><img :src="TipIcon" class="w-4 h-4 mr-2" /></span>
        {{ $t('trackMgr.draftTip') }}
      </div>
      <div>
        <el-button type="primary" link @click="handleContinueEdit">{{ $t('trackMgr.continueEdit') }}</el-button>
        <el-button type="primary" link @click="handleDeleteDraft">{{ $t('trackMgr.delete') }}</el-button>
      </div>
    </div>
    <div class="h-[75vh] mt-5">
      <el-form ref="formRef" :model="localFormData" :rules="rules" label-width="auto">
        <!-- 第一行：赛道名称和所属分组 -->
        <div class="flex mb-0.5">
          <el-form-item :label="$t('trackMgr.trackName')" prop="name" class="mr-10 ml-5 flex-1">
            <el-input v-model="localFormData.name" :placeholder="$t('common.inputPhTxt')" maxlength="50" />
          </el-form-item>
          <el-form-item :label="$t('trackMgr.technosphere')" prop="technosphere" class="flex-1">
            <el-select v-model="localFormData.technosphere" :placeholder="$t('common.selectPhTxt')" class="w-full">
              <el-option v-for="item in technosphereList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </div>
        <!-- 第二行：所属大赛和组别 -->
        <div class="flex mb-0.5">
          <el-form-item :label="$t('trackMgr.belongCompetition')" prop="compId" class="mr-10 ml-5 flex-1">
            <el-select v-model="localFormData.compId" :placeholder="$t('common.selectPhTxt')" class="w-full"
              @change="handleCompetitionChange">
              <el-option v-for="item in options.competitions" :key="item.value" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('trackMgr.groupName')" prop="compGroupId" class="flex-1">
            <el-select v-model="localFormData.compGroupId" :placeholder="$t('common.selectPhTxt')" class="w-full">
              <el-option v-for="item in options.groups" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </div>
        <!-- 第三行：所属月份和分组时间 -->
        <div class="flex mb-0.5">
          <el-form-item :label="$t('trackMgr.belongMonth')" prop="belongMonth" class="mr-10 ml-5 flex-1">
            <el-date-picker v-model="localFormData.belongMonth" type="month" :placeholder="$t('common.selectPhTxt')"
              style="width: 100%" />
          </el-form-item>
          <el-form-item :label="$t('trackMgr.registrationTime')" prop="registrationTime" class="flex-1">
            <el-date-picker v-model="localFormData.registrationTime" type="daterange"
              :range-separator="$t('common.rangeSeparatorTxt')" style="width: 100%" value-format="YYYY-MM-DD HH:mm:ss"
              :unlink-panels="true" :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)]"
              :start-placeholder="$t('common.startTimeTxt')" :end-placeholder="$t('common.endTimeTxt')" />
          </el-form-item>
        </div>
        <!-- 赛道描述 -->
        <el-form-item :label="$t('trackMgr.trackIntro')" prop="intro" class="ml-5 mb-3">
          <el-input v-model="localFormData.intro" :rows="6" type="textarea" :placeholder="$t('common.inputPhTxt')"
            maxlength="1000" show-word-limit />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">{{ $t('common.cancelTxt') }}</el-button>
        <el-button @click="handleConfirm('preserve')" :loading="loading" class="w-20">
          {{ $t('trackMgr.save') }}
        </el-button>
        <el-button type="primary" @click="handleConfirm('publish')" :loading="loadingPublish" class="w-20">
          {{ $t('trackMgr.publish') }}
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, watch, computed, onMounted } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { $t } from '@vben/locales';
import deleteIcon from '#/assets/images/delete-icon.png';
import type { FormInstance, FormRules } from 'element-plus';
import dayjs from 'dayjs';
import { createCompTrackApi, updateCompTrackApi, saveCompTrackDraftApi } from '#/api/competition/track-mgr';
import { getCompGroupPageApi } from '#/api/competition/competitionCtgr';
import { queryMatchListApi } from '#/api/competition/competition-list';
import TipIcon from '#/assets/images/tip-icon.svg'

// 类型定义
interface Props {
  modelValue: boolean;
  formData: any;
  mode: 'add' | 'edit';
  technosphereList: any[];
}

// Props 和 Emits
const props = defineProps<Props>();
const emit = defineEmits<{
  'update:modelValue': [value: boolean];
  success: [actionType: 'preserve' | 'publish'];
  cancel: [];
  draftDeleted: [];
}>();

// 核心数据
const formRef = ref<FormInstance>();
const localFormData = ref<any>({});
const originalFormData = ref<any>({});

// 简化状态管理
const loading = ref(false);
const loadingPublish = ref(false);
const isProcessing = ref(false);

// 草稿状态
const draft = ref({
  hasDraft: false,
  data: null as any,
});

// 下拉选项
const options = ref({
  competitions: [] as any[],
  groups: [] as any[],
});

// 动态错误消息
const nameFieldError = ref('');

// 自定义name字段验证器
const validateName = (_rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error($t('trackMgr.validationTrackName')));
    return;
  }
  if (nameFieldError.value) {
    callback(new Error(nameFieldError.value));
    return;
  }
  callback();
};

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: $t('trackMgr.validationTrackName'), trigger: 'blur' },
    { validator: validateName, trigger: 'blur' }
  ],
  technosphere: [{ required: true, message: $t('trackMgr.validationTechnosphere'), trigger: 'change' }],
  compId: [{ required: true, message: $t('trackMgr.validationCompId'), trigger: 'change' }],
  compGroupId: [{ required: true, message: $t('trackMgr.validationGroupId'), trigger: 'change' }],
  belongMonth: [{ required: true, message: $t('trackMgr.validationBelongMonth'), trigger: 'change' }],
  registrationTime: [{ required: true, message: $t('trackMgr.validationRegistrationTime'), trigger: 'change' }],
};

// 检查表单是否有修改
const isFormChanged = computed(() => {
  if (!localFormData.value || !originalFormData.value) return false;

  const current = JSON.stringify(localFormData.value);
  const original = JSON.stringify(originalFormData.value);
  return current !== original;
});

// ===== 工具函数 =====
// 格式化表单数据
const formatFormData = (data: any) => {
  const paramData = JSON.parse(JSON.stringify(data));
  const { registrationTime } = paramData;

  if (registrationTime && registrationTime.length > 0) {
    paramData.registrationStartTime = registrationTime[0];
    paramData.registrationEndTime = registrationTime[1];
    paramData.belongMonth = dayjs(paramData.belongMonth).format('YYYY-MM');
  }

  return paramData;
};

// 检查必填项
const validateRequiredFields = () => {
  const requiredFields = ['name', 'technosphere', 'compId', 'compGroupId', 'belongMonth', 'registrationTime'];
  return requiredFields.every(field => localFormData.value[field]);
};

// 显示确认对话框
const showConfirmDialog = async (message: string) => {
  return ElMessageBox.confirm('', {
    title: '',
    message: `
      <div style="display: flex; align-items: center;">
        <img src="${deleteIcon}" style="width: 48px; height: 48px; margin-right: 10px;" />
        <span>${message}</span>
      </div>
    `,
    confirmButtonText: $t('competition.yes'),
    cancelButtonText: $t('competition.no'),
    customClass: 'delete-dialog',
    dangerouslyUseHTMLString: true,
    center: false,
    distinguishCancelAndClose: true,
  });
};

// ===== API 调用 =====
// 加载大赛列表
const loadCompetitions = async () => {
  try {
    const res = await queryMatchListApi();
    options.value.competitions = res.map((item: any) => ({
      label: item.matchName,
      value: item.id
    }));
  } catch (error) {
    options.value.competitions = [];
  }
};

// 加载组别列表
const loadGroups = async (compId: string) => {
  if (!compId) {
    options.value.groups = [];
    return;
  }

  try {
    const res = await getCompGroupPageApi({ compId });
    options.value.groups = res?.data?.length
      ? res.data.map((item: any) => ({ label: item.name, value: item.id }))
      : [];
  } catch (error) {
    options.value.groups = [];
  }
};

// 大赛选择变化处理
const handleCompetitionChange = async (compId: string) => {
  localFormData.value.compGroupId = '';
  await loadGroups(compId);
};

// ===== 核心业务逻辑 =====
// API调用处理
const handleApiCall = async (paramData: any, type: 'preserve' | 'publish') => {
  const cleanData = { ...paramData };
  delete cleanData.draft;
  delete cleanData.isDraft;

  try {
    if (props.mode === 'add') {
      // 新增赛道
      await createCompTrackApi(cleanData);
    } else if (props.formData.releaseStatus === 1 && type === 'preserve') {
      // 已发布的内容则保存草稿
      await saveCompTrackDraftApi(cleanData);
    } else {
      // 保存未发布的内容或者点击发布按钮
      if (type === 'publish') {
        cleanData.releaseStatus = 1; // 发布状态
      }
      await updateCompTrackApi(cleanData);
    }
    // 成功后关闭并触发事件
    emit('update:modelValue', false);
    emit('success', type);

  } catch (error) {
    // 移除 console.error 调试语句

    // 检查是否是表单验证错误（状态码7002）
    if ((error as any)?.status == 7002) {
      // 设置name字段的错误消息
      nameFieldError.value = (error as any)?.message || $t('trackMgr.duplicateTrackNameError');

      // 触发name字段的验证以显示错误
      if (formRef.value) {
        formRef.value.validateField('name');
      }
      throw error;
    }

    // ElMessage.error($t('trackMgr.operationFailed'));
    throw error;
  }
};

// ===== 草稿处理 =====
// 继续编辑草稿
const handleContinueEdit = async () => {
  if (!draft.value.data) return;

  draft.value.hasDraft = false;
  const draftData = draft.value.data;

  // 恢复草稿数据
  localFormData.value = JSON.parse(JSON.stringify(draftData));

  // 处理时间格式转换
  if (draftData.registrationStartTime && draftData.registrationEndTime) {
    localFormData.value.registrationTime = [
      draftData.registrationStartTime,
      draftData.registrationEndTime
    ];
  }

  // 确保下拉选项已加载
  if (draftData.compId) {
    if (options.value.competitions.length === 0) {
      await loadCompetitions();
    }
    await loadGroups(draftData.compId);
  }
};

// 删除草稿
const handleDeleteDraft = async () => {
  try {
    await showConfirmDialog($t('trackMgr.draftDeleteConfirm'));
    await saveCompTrackDraftApi({ id: props.formData.id, draftDeleted: "Y" });
    draft.value.hasDraft = false;
    draft.value.data = null;
    ElMessage.success($t('trackMgr.deleteDraftSuccessMsg'));
    emit('draftDeleted');
  } catch (error) {
    if (error !== 'cancel') {
      // 移除 console.error 调试语句
    }
  }
};

// ===== 数据初始化 =====
// 初始化表单数据
const initializeFormData = async (formData: any) => {
  if (!formData || Object.keys(formData).length === 0) return;

  // 处理草稿数据
  if (formData.draft && props.mode === 'edit') {
    draft.value.hasDraft = true;
    try {
      draft.value.data = typeof formData.draft === 'string'
        ? JSON.parse(formData.draft)
        : formData.draft;
    } catch (error) {
      // 移除 console.error 调试语句
      draft.value.hasDraft = false;
      draft.value.data = null;
    }
  } else {
    draft.value.hasDraft = false;
    draft.value.data = null;
  }

  // 初始化表单数据
  localFormData.value = JSON.parse(JSON.stringify(formData));
  originalFormData.value = JSON.parse(JSON.stringify(formData));

  // 加载对应的组别列表
  if (formData.compId) {
    await loadGroups(formData.compId);
  }
};

// ===== 监听器 =====
watch(() => props.formData, initializeFormData, { immediate: true, deep: true });

watch(() => options.value.groups, (newOptions) => {
  if (localFormData.value.compGroupId && newOptions?.length > 0) {
    const isValidGroup = newOptions.some((option: any) =>
      option.value === localFormData.value.compGroupId
    );
    if (!isValidGroup) {
      localFormData.value.compGroupId = '';
    }
  }
}, { deep: true });

// 监听name字段变化，清除错误状态
watch(() => [localFormData.value.name, localFormData.value.compId, localFormData.value.compGroupId], () => {
  if (nameFieldError.value) {
    nameFieldError.value = '';
    // 重新验证name字段以清除错误显示
    if (formRef.value) {
      formRef.value.validateField('name');
    }
  }
});

onMounted(async () => {
  await loadCompetitions();
});

// ===== 主要操作处理 =====
// 保存和发布处理
const handleConfirm = async (type: 'preserve' | 'publish') => {
  if (!formRef.value) return;

  try {
    // 表单验证
    await formRef.value.validate();

    // 校验必填项
    if (!validateRequiredFields()) {
      ElMessage.warning($t('competition.incompleteInfo'));
      return;
    }

    // 设置loading状态
    if (type === 'preserve') {
      loading.value = true;
    } else {
      loadingPublish.value = true;
    }

    // 处理表单数据
    const paramData = formatFormData(localFormData.value);
    paramData.releaseStatus = type === 'publish' ? 1 : 0;

    // 调用API
    await handleApiCall(paramData, type);

    // 显示成功消息
    ElMessage.success(type === 'publish' ? $t('trackMgr.publishSuccessMsg') : $t('trackMgr.saveSuccessMsg'));

  } catch (error) {
    if (error !== 'cancel') {
      // 移除 console.error 调试语句
    }
  } finally {
    loading.value = false;
    loadingPublish.value = false;
  }
};

// ===== 关闭和取消处理 =====
// 关闭前检查
const handleBeforeClose = async (done: () => void) => {
  const canClose = await handleCancelLogic();
  if (canClose) {
    emit('cancel');
    done();
  }
};

// 抽屉关闭
const handleDrawerClose = (value: boolean) => {
  emit('update:modelValue', value);
};

// 取消逻辑
const handleCancelLogic = async (): Promise<boolean> => {
  // 防止重复处理
  if (isProcessing.value) return false;

  // 检查是否有未保存的修改
  if (isFormChanged.value) {
    isProcessing.value = true;

    try {
      await showConfirmDialog($t('trackMgr.unsavedDataConfirmExit'));
      formRef.value?.resetFields?.();
      return true;
    } catch (error) {
      return false;
    } finally {
      isProcessing.value = false;
    }
  } else {
    // 没有修改，直接关闭
    formRef.value?.resetFields?.();
    return true;
  }
};

// 取消按钮
const handleCancel = async () => {
  const canClose = await handleCancelLogic();
  if (canClose) {
    emit('update:modelValue', false);
    emit('cancel');
  }
};
</script>
